// Copyright (c) 2024, the WwMusic project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

package com.springfairy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.springfairy.dao.MoodDiaryMapper;
import com.springfairy.model.MoodDiary;
import com.springfairy.service.MoodDiaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;

@Service
public class MoodDiaryServiceImpl implements MoodDiaryService {

    @Autowired
    private MoodDiaryMapper moodDiaryMapper;

    @Override
    public MoodDiary writeDiary(MoodDiary diary) {
        // 根据 userId 和 diaryDate 判断是新增还是更新（UNIQUE约束）
        LambdaQueryWrapper<MoodDiary> query = new LambdaQueryWrapper<MoodDiary>()
                .eq(MoodDiary::getUserId, diary.getUserId())
                .eq(MoodDiary::getDiaryDate, diary.getDiaryDate());
        MoodDiary existing = moodDiaryMapper.selectOne(query);
        if (existing != null) {
            diary.setId(existing.getId());
            moodDiaryMapper.updateById(diary);
        } else {
            diary.setId(moodDiaryMapper.insert(diary));
        }
        return diary;
    }

    @Override
    public MoodDiary getDiaryByUserAndDate(int userId, LocalDate date) {
        return moodDiaryMapper.selectOne(new LambdaQueryWrapper<MoodDiary>()
                .eq(MoodDiary::getUserId, userId)
                .eq(MoodDiary::getDiaryDate, date));
    }

    @Override
    public List<MoodDiary> getAllDiariesByUser(int userId) {
        return moodDiaryMapper.selectList(new LambdaQueryWrapper<MoodDiary>()
                .eq(MoodDiary::getUserId,userId)
        );
    }


    @Override
    public void updateDiary(MoodDiary diary) {
        moodDiaryMapper.updateById(diary);
    }

    @Override
    public boolean deleteDiary(int deleteDiary) {
        return moodDiaryMapper.deleteById(deleteDiary) > 0;
    }
}

